<?php

	$classes = null;
	$directories = null;
	$isDebugging = false;
	$root = realpath(".");
	$protected = "quasenadafw/IncludeWrapper.php";

	function __autoload($class_name) {
		global $classes, $directories, $root, $protected;		
		
		if( $directories == null ) loadDirectories($root);
		if( $classes == null ) loadClasses();

		foreach( $classes as $class ) {
			$name = substr($class, strrpos($class, "/") + 1, strlen($class));
			$name = str_replace(".php", "", $name);
			
			if( $name == $class_name && $protected != $class ) {
				debug("Classe '$class' sendo carregada pelo __autoload");
				require $class;
			}
		}
	}
		
	function loadDirectories($directory) {
		global $directories;
						
		if( $directories == null ) $directories = array();
		
		if( is_dir( $directory ) ) {
			//debug("Adicionando o diretorio <b>$directory</b> a lista de processamento");
			$directories[] = $directory;
			$dirs = scandir($directory);

			foreach ( $dirs as $dir ) {
				$dir = $directory . "/" . $dir;
				if( is_dir($dir) && substr($dir, strlen($dir)- 1) != "." && substr($dir, strlen($dir)- 2) != ".." ) {
					loadDirectories($dir);
				}									
			}
		}		
	}
	
	function loadClasses() {
		global $directories, $classes, $root;
		
		foreach( $directories as $directory ) {
			debug("Processando o diretorio <b>$directory</b>");
			
			$files = scandir($directory);
			foreach( $files as $file ) {
				$file = $directory . "/" . $file;
				debug("Arquivo encontrado: '$file'");
				$extension = substr($file, strlen($file)-4, strlen($file));
				
				if( is_file($file) && $extension == ".php" ) { // verifica se e arquivo e se e php
					$include_file = $directory . "/" .$file;
					debug("<b>Adicionando a classe $include_file ao classpath</b>");
					$classes[] = $file;
				}
			}
		}		
	}
	
	function debug($message) {
		global $isDebugging;
		if($isDebugging) {
			echo "Debug Message on " . date("l dS \of F Y h:i:s A") . " : $message <br />";
		}
	}
?>